package com.hfy.pcberpbackend.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hfy.pcberpbackend.entity.Employee;
import com.hfy.pcberpbackend.mapper.EmployeeMapper;
import com.hfy.pcberpbackend.service.EmployeeService;
import com.hfy.pcberpbackend.dto.EmployeeQueryDTO;
import com.hfy.pcberpbackend.common.PageResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.util.StrUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

/**
 * 员工Service实现类
 */
@Slf4j
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {
    
    @Override
    public PageResult<Employee> getEmployeePage(EmployeeQueryDTO query) {
        log.info("分页查询员工列表，查询条件：{}", query);
        
        Page<Employee> page = new Page<>(query.getPage(), query.getSize());
        IPage<Employee> result = baseMapper.selectEmployeePage(page, query);
        
        return PageResult.of(result.getRecords(), result.getTotal(), 
                           result.getCurrent(), result.getSize());
    }
    
    @Override
    public Employee getEmployeeById(Long id) {
        log.info("根据ID获取员工详情，ID：{}", id);
        
        Employee employee = getById(id);
        if (employee == null) {
            throw new RuntimeException("员工不存在");
        }
        return employee;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createEmployee(Employee employee) {
        log.info("新增员工：{}", employee);
        
        // 检查员工代码是否存在
        if (isEmployeeCodeExists(employee.getEmployeeCode(), null)) {
            throw new RuntimeException("员工代码已存在");
        }
        
        // 设置默认状态
        if (StrUtil.isBlank(employee.getStatus())) {
            employee.setStatus("active");
        }
        
        save(employee);
        return employee.getId();
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateEmployee(Long id, Employee employee) {
        log.info("更新员工信息，ID：{}，数据：{}", id, employee);
        
        // 检查员工是否存在
        Employee existingEmployee = getEmployeeById(id);
        
        // 检查员工代码是否重复（排除自己）
        if (StrUtil.isNotBlank(employee.getEmployeeCode()) && 
            !employee.getEmployeeCode().equals(existingEmployee.getEmployeeCode()) &&
            isEmployeeCodeExists(employee.getEmployeeCode(), id)) {
            throw new RuntimeException("员工代码已存在");
        }
        
        // 更新数据
        employee.setId(id);
        updateById(employee);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteEmployee(Long id) {
        log.info("删除员工，ID：{}", id);
        
        // 检查员工是否存在
        getEmployeeById(id);
        
        // TODO: 检查是否有关联的客户记录
        // 如果有客户关联此员工作为业务经理，应该阻止删除或提示转移客户
        
        // 逻辑删除
        removeById(id);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchDeleteEmployees(List<Long> ids) {
        log.info("批量删除员工，IDs：{}", ids);
        
        if (ids == null || ids.isEmpty()) {
            throw new RuntimeException("删除的ID列表不能为空");
        }
        
        // TODO: 批量检查是否有关联的客户记录
        
        // 批量逻辑删除
        removeByIds(ids);
    }
    
    @Override
    public List<Map<String, Object>> getManagerOptions() {
        log.info("获取业务经理选项");
        return baseMapper.selectManagerOptions();
    }
    
    @Override
    public List<Map<String, String>> getEmployeeRoles() {
        List<Map<String, String>> roles = new ArrayList<>();
        
        Map<String, String> manager = new HashMap<>();
        manager.put("value", "manager");
        manager.put("label", "业务经理");
        roles.add(manager);
        
        Map<String, String> admin = new HashMap<>();
        admin.put("value", "admin");
        admin.put("label", "管理员");
        roles.add(admin);
        
        return roles;
    }
    
    @Override
    public boolean isEmployeeCodeExists(String employeeCode, Long excludeId) {
        if (StrUtil.isBlank(employeeCode)) {
            return false;
        }
        
        int count = baseMapper.countByEmployeeCode(employeeCode, excludeId);
        return count > 0;
    }
    
    @Override
    public List<Employee> searchEmployees(String keyword, String role, Integer size) {
        log.info("模糊搜索员工，关键词：{}，角色：{}，数量限制：{}", keyword, role, size);
        
        if (StrUtil.isBlank(keyword)) {
            return new ArrayList<>();
        }
        
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<>();
        wrapper.and(qw -> qw
                .like(Employee::getEmployeeCode, keyword)
                .or()
                .like(Employee::getEmployeeName, keyword)
        );
        wrapper.eq(Employee::getStatus, "active");
        
        // 如果指定了角色，添加角色过滤
        if (StrUtil.isNotBlank(role)) {
            wrapper.eq(Employee::getRole, role);
        }
        
        wrapper.orderByDesc(Employee::getUpdatedAt);
        
        if (size != null && size > 0) {
            wrapper.last("LIMIT " + size);
        }
        
        return list(wrapper);
    }
} 